package com.ias.agdis_r.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.Ndef;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.more.WorkGroupActivity;
import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.bean.user.UserInfoBean;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.binding.endpoint.request.ManCarBindingRequest;
import com.ias.agdis_r.terminalmanager.restful.binding.vo.ManCarBindingRequestVO;
import com.ias.agdis_r.terminalmanager.restful.workgroup.vo.Member;
import com.ias.agdis_r.util.network.HttpUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Locale;

@SuppressLint("NewApi")
public class NFCUtil {
	public static int[] s70_4k_key = {7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47, 51, 55, 59, 63, 67, 71, 75, 79, 83, 87, 91, 95, 99, 103, 107, 111, 115, 119, 123, 127, 143, 159, 175, 191, 207, 223, 239, 255};
	public static byte keyA[] = {(byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0xAA,
			(byte) 0xAA, (byte) 0xAB};
	public static void handleActionNDEF(Activity activity, Intent intent, NfcAdapter mNfcAdapter) {
		Object[] data = onNewIntentNDEF(intent, mNfcAdapter);
		if (null != data) {
			if (MessageModel.bindCar.equals(data[0])) {
				String vnb = (String) data[1];
				if (S.isNotEmpty(vnb)) {
					showBindConfirm(activity, vnb);
				}
			} else if (MessageModel.workGroup.equals(data[0])) {
				if (null != data[1]) {
					Member member = (Member) data[1];
					if (null != JavaBeanManager.getInstance().getUserinfo() && JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_WORKGROUP.toString())) {
						Intent workGroupIntent = new Intent(activity, WorkGroupActivity.class);
						workGroupIntent.putExtra(MessageModel.workGroup, member);
						workGroupIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						activity.startActivity(workGroupIntent);
					}
				}
			}
		}
	}

	public static String readTag(Tag tag){
		String value = "";
		String[] techList = tag.getTechList();
//		if(type.equals(MifareClassic.class.getName())){
//
//			System.out.println("读取"+MifareClassic.class.getSimpleName()+"标签");
//			value = readMifareClassicTag(tag);
//
//		}else if(type.equals(MifareUltralight.class.getName())){
//
//			System.out.println("读取"+MifareUltralight.class.getSimpleName()+"标签");
//			value = readMifareUltralightTag(tag);
//
//		}else if(type.equals(NfcA.class.getName())){
//
//			System.out.println("读取"+NfcA.class.getSimpleName()+"标签");
//			value = readNfcATag(tag);
//
//		}else if(type.equals(Ndef.class.getName())){
			System.out.println("读取"+Ndef.class.getSimpleName()+"标签");
			value = readNdefTag(tag);
//		}
		return value;
	}

	public static boolean writeTag(Tag tag,String value){
		boolean flag = false;
		flag = writeNdefTag(tag,value);
//		if(type.equals(MifareClassic.class.getName())){
//
//			flag = writeMifareClassicTag(tag,value);
//
//		}else if(type.equals(MifareUltralight.class.getName())){
//
//			flag = writeMifareUltralightfTag(tag,value);
//
//		}else if(type.equals(NfcA.class.getName())){
//
//			//flag = writeNfcAfTag(tag,value);
//
//		}else if(type.equals(Ndef.class.getName())){
//
//			flag = writeNdefTag(tag,value);
//		}
		return flag;
	}

	private static String readNdefTag(Tag tag) {
		String value = "";
		Ndef ndef = Ndef.get(tag);
		try {
			ndef.connect();
			String type = ndef.getType();//获取TAG的类型
			NdefMessage message = ndef.getNdefMessage();
			if (null != message) {
				NdefRecord[] ndefRecord = message.getRecords();
				value = parse(ndefRecord[0]);
			}
		} catch (Exception e) {
			e.printStackTrace();
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, DataBaseManager.getInstance().getContext().getString(R.string.readTagErr), false);
		} finally {
			try {
				ndef.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return value;
	}

	//  将纯文本内容从NdefRecord对象（payload）中解析出来
	private static String parse(NdefRecord record) {
		//验证TNF是否为NdefRecord.TNF_WELL_KNOWN
		if (record.getTnf() != NdefRecord.TNF_WELL_KNOWN)
			return null;
		//验证可变长度类型是否为RTD_TEXT
		if (!Arrays.equals(record.getType(), NdefRecord.RTD_TEXT))
			return null;

		try {
			//获取payload
			byte[] payload = record.getPayload();
			//下面代码分析payload：状态字节+ISO语言编码（ASCLL）+文本数据（UTF_8/UTF_16）
			//其中payload[0]放置状态字节：如果bit7为0，文本数据以UTF_8格式编码，如果为1则以UTF_16编码
			//bit6是保留位，默认为0
            /*
             * payload[0] contains the "Status Byte Encodings" field, per the
             * NFC Forum "Text Record Type Definition" section 3.2.1.
             *
             * bit7 is the Text Encoding Field.
             *
             * if (Bit_7 == 0): The text is encoded in UTF-8 if (Bit_7 == 1):
             * The text is encoded in UTF16
             *
             * Bit_6 is reserved for future use and must be set to zero.
             *
             * Bits 5 to 0 are the length of the IANA language code.
             */
			String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8"
					: "UTF-16";
			//处理bit5-0。bit5-0表示语言编码长度（字节数）
			int languageCodeLength = payload[0] & 0x3f;
			//获取语言编码（从payload的第2个字节读取languageCodeLength个字节作为语言编码）
			String languageCode = new String(payload, 1, languageCodeLength,
					"US-ASCII");
			//解析出实际的文本数据
			String text = new String(payload, languageCodeLength + 1,
					payload.length - languageCodeLength - 1, textEncoding);
			//创建一个TextRecord对象，并返回该对象
			return text;
		} catch (UnsupportedEncodingException e) {
			// should never happen unless we get a malformed tag.
			throw new IllegalArgumentException(e);
		}
	}

	private static boolean writeNdefTag(Tag tag,String value){
		Ndef ndef=Ndef.get(tag);
		try {
			ndef.connect();
			NdefMessage ndefMessage = new NdefMessage(
					new NdefRecord[] {createTextRecord(value)});
			ndef.writeNdefMessage(ndefMessage);
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (FormatException e) {
			e.printStackTrace();
		}finally {
			try {
				ndef.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	//创建一个封装要写入的文本的NdefRecord对象
	private static NdefRecord createTextRecord(String text) {
		//生成语言编码的字节数组，中文编码
		byte[] langBytes = Locale.CHINA.getLanguage().getBytes(
				Charset.forName("US-ASCII"));
		//将要写入的文本以UTF_8格式进行编码
		Charset utfEncoding = Charset.forName("UTF-8");
		//由于已经确定文本的格式编码为UTF_8，所以直接将payload的第1个字节的第7位设为0
		byte[] textBytes = text.getBytes(utfEncoding);
		int utfBit = 0;
		//定义和初始化状态字节
		char status = (char) (utfBit + langBytes.length);
		//创建存储payload的字节数组
		byte[] data = new byte[1 + langBytes.length + textBytes.length];
		//设置状态字节
		data[0] = (byte) status;
		//设置语言编码
		System.arraycopy(langBytes, 0, data, 1, langBytes.length);
		//设置实际要写入的文本
		System.arraycopy(textBytes, 0, data, 1 + langBytes.length,
				textBytes.length);
		//根据前面设置的payload创建NdefRecord对象
		NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
				NdefRecord.RTD_TEXT, new byte[0], data);
		return record;
	}

	private static Object[] onNewIntentNDEF(Intent intent, NfcAdapter mNfcAdapter) {
		Object[] data = null;
		if (mNfcAdapter == null) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, DataBaseManager.getInstance().getContext().getString(R.string.NfcNotSupport), false);
		} else if (!mNfcAdapter.isEnabled()) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, DataBaseManager.getInstance().getContext().getString(R.string.openNfc), false);
		} else {
			Tag tag = intent.getParcelableExtra(mNfcAdapter.EXTRA_TAG);
			if (null == tag) {
				return data;
			}
			if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_WORKGROUP.toString())) {
				MifareClassic mifareClassic = MifareClassic.get(tag);
				if (null == mifareClassic) {
					EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, DataBaseManager.getInstance().getContext().getString(R.string.notNdef), false);
					return data;
				}
				String text = readMifareClassicTag(tag);
				if (S.isNotEmpty(text)) {
					data = new Object[2];
					data[0] = MessageModel.workGroup;
					try {
						Member member = DataManager.getInstance().getMapper().readValue(text, Member.class);
						data[1] = member;
						EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, DataBaseManager.getInstance().getContext().getString(R.string.readNfcGroupMember) + member.getMember_name(), false);
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, DataBaseManager.getInstance().getContext().getString(R.string.notReadNfcData), false);
				}
			} else if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_USERCARBIND.toString())) {
				Ndef ndef = Ndef.get(tag);
				if (null == ndef) {
					EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, DataBaseManager.getInstance().getContext().getString(R.string.notNdef), false);
					return data;
				}
				String text = readNdefTag(tag);
				if (S.isNotEmpty(text)) {
					if (text.startsWith("\"bindCar\":\"")) {
						data = new Object[2];
						data[0] = MessageModel.bindCar;
						data[1] = text.substring(11, text.length() - 1);
						EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, DataBaseManager.getInstance().getContext().getString(R.string.readNfcVnb) + data[1].toString(), false);
					}
				} else {
					EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, DataBaseManager.getInstance().getContext().getString(R.string.notReadNfcData), false);
				}
			}
		}
		return data;
	}

	private static Dialog dialog;
	/**
	 * 显示绑定车号弹出框
	 */
	public static void showBindConfirm(final Activity activity, String scanVnb){
		//如果没有人车绑定权限
		if(!JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_USERCARBIND.toString())){
			return;
		}
		//获取用户信息
		UserInfoBean userinfo = JavaBeanManager.getInstance().getUserinfo();
		if (userinfo == null) {
			return;
		}
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
		//获取当前用户车号
		final String vnb = S.valueOf(userinfo.getVnb());
		AlertDialog.Builder dialogb = new AlertDialog.Builder(activity);
		LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.dialog, null);
		dialogb.setTitle(activity.getString(R.string.inputCarnum));
		dialogb.setView(layout);
		final EditText txt_carnum = (EditText)layout.findViewById(R.id.edit_content);
		dialogb.setPositiveButton(activity.getString(R.string.bind), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				String myvnb = S.valueOf(txt_carnum.getText());
				if (S.isEmpty(myvnb)) {
					ShowToast.get().show(activity.getString(R.string.inputCarnum));
				} else if (!vnb.equals(myvnb)) {
					bindCarNum(myvnb);
				}
			}
		});
		if(S.isNotEmpty(vnb)) {
			dialogb.setNeutralButton(activity.getString(R.string.unbind), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					bindCarNum("");
				}
			});
		}
		dialogb.setNegativeButton(activity.getString(R.string.cancel), null);
		dialog = dialogb.create();
		if (S.isNotEmpty(scanVnb) && scanVnb.length() <= 10){
			txt_carnum.setText(scanVnb);
			txt_carnum.setEnabled(false);
		}else{
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, activity.getString(R.string.inputCarnum), false);
			txt_carnum.setText(vnb);
			txt_carnum.setOnFocusChangeListener(new View.OnFocusChangeListener() {
				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) {
						dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
					}
				}
			});
		}
		dialog.show();
		txt_carnum.requestFocus();
	}

	/**
	 * 绑定车号
	 */
	private static void bindCarNum(String vnb){
		HttpUtil.getInstance().sendRequest(initUCBD(vnb), MessageModel.UCBD, true);
	}

	private static ManCarBindingRequest initUCBD(String vnb){
		ManCarBindingRequest manCarBindingRequest = new ManCarBindingRequest();
		ManCarBindingRequestVO manCarBindingRequestVO = new ManCarBindingRequestVO();
		manCarBindingRequestVO.setVnb(vnb);
		manCarBindingRequestVO.setFlg("Y");
		if (S.isNotEmpty(vnb)){
			manCarBindingRequestVO.setTst("Y");
		}else{
			manCarBindingRequestVO.setTst("N");
		}
		manCarBindingRequest.setManCarBindingRequestVO(manCarBindingRequestVO);
		return manCarBindingRequest;
	}

	public static String readMifareClassicTag(Tag tag) {
		byte[] mData = new byte[4096];
		int totalLength = 0;
		MifareClassic mifareClassic = MifareClassic.get(tag);
		try {
			mifareClassic.connect();
			int sectorCount = mifareClassic.getSectorCount();
			boolean auth;
			for (int j = 1; j < sectorCount; j++) {
				auth = mifareClassic.authenticateSectorWithKeyA(j, keyA);
				int bCount;
				int bIndex;
				if (auth) {
					bCount = mifareClassic.getBlockCountInSector(j);
					bIndex = mifareClassic.sectorToBlock(j);
					for (int i = 0; i < bCount; i++) {
						if (!isKeyBlock(bIndex)) {
							byte[] data = mifareClassic.readBlock(bIndex);
							System.arraycopy(data, 0, mData, totalLength, data.length);
							totalLength = totalLength + data.length;
						}
						bIndex++;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (mifareClassic != null) {
				try {
					mifareClassic.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		String value = "";
		try {
			value = new String(mData, "GBK").replace("\u0000", "");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return value;
	}

	private static boolean isKeyBlock(int index) {
		for (int i = 0; i < s70_4k_key.length; i++) {
			if (s70_4k_key[i] == index) {
				return true;
			}
		}
		return false;
	}

	public static boolean writeMifareClassicTag(Tag tag, String value) {
		MifareClassic mfc = MifareClassic.get(tag);
		try {
			mfc.connect();
			boolean auth = false;
			short sectorAddress = 0;
			auth = mfc.authenticateSectorWithKeyB(sectorAddress, MifareClassic.KEY_DEFAULT);
			if (auth) {
				// the last block of the sector is used for KeyA and KeyB cannot
				// be overwritted
				mfc.writeBlock(sectorAddress, "1234567890ABCDEF".getBytes(Charset.forName("GBK")));
				System.out.println("writeMifareClassicTag写入成功");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				mfc.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
}
